package com.ssm.tool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPoolUtils {

    private ThreadPoolUtils() {}

    public static void shutDownPool(ExecutorService pool, int shutDownTimeOut,
                                    int shutDownNowTimeOut, TimeUnit timeUnit) {
        pool.shutdown(); //先调用一次shutdown

        try {
            if(!pool.awaitTermination(shutDownTimeOut, timeUnit)) { //判断指定时间后的线程池是否关闭
                pool.shutdownNow(); //如果超时还未关闭，则暴力关闭
                if(!pool.awaitTermination(shutDownNowTimeOut, timeUnit)) { //暴力关闭后，等待指定时间后再检验线程池是否关闭
                    log.error("ThreadPoolUtils.shutDownPool.erroe"); //暴力还未关闭，则证明线程池存在问题
                }
            }
        } catch (InterruptedException e) {
            // 外部线程被打断了，就会抛出该打断异常
            log.error("ThreadPoolUtils.shutDownPool.interrupted.error:{}", e.getMessage(), e);
            // 直接把线程池关闭
            pool.shutdownNow();
            // 直接将当前关闭线程给中断
            Thread.currentThread().interrupt();
        }
    }

}
